﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Xml.Linq;
using System.Windows.Browser;

namespace Dropthing.Silverlight
{
    public partial class Page : UserControl
    {
        private XElement _State;
        private XElement State
        {
            get
            {
                if (_State == null) _State = XElement.Parse("<state><topic>football</topic></state>");
                return _State;
            }
            set
            {
                _State = value;
            }
        }

        public string Topic
        {
            get { return (State.Element("topic") ?? new XElement("topic", "")).Value; }
            set { State.Element("topic").Value = value; }
        }

        private void GetState()
        {
            App myApp = Application.Current as App;

            if (myApp.InitParams.ContainsKey("WidgetId"))
            {
                int WidgetId = Convert.ToInt32(myApp.InitParams["WidgetId"]);
                DropthingsWebService.WidgetServiceSoapClient service = new DropthingsWebService.WidgetServiceSoapClient();
                service.GetWidgetStateCompleted += new EventHandler<DropthingsWebService.GetWidgetStateCompletedEventArgs>(service_GetWidgetStateCompleted);
                service.GetWidgetStateAsync(WidgetId);
            }
        }

        public void service_GetWidgetStateCompleted(object sender, DropthingsWebService.GetWidgetStateCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                this.State = XElement.Parse(e.Result);
                txtSearchTopic.Text = this.Topic;
                DoSearch();
            }
        }

        private void SaveState()
        {
            App myApp = Application.Current as App;

            if (myApp.InitParams.ContainsKey("WidgetId"))
            {
                int WidgetId = Convert.ToInt32(myApp.InitParams["WidgetId"]);
                DropthingsWebService.WidgetServiceSoapClient service = new DropthingsWebService.WidgetServiceSoapClient();
                service.SaveWidgetStateAsync(WidgetId, State.ToString());
            }
        }

        public Page()
        {
            InitializeComponent();
            this.Height = System.Double.NaN;
            this.Width = System.Double.NaN;
            this.Loaded += new RoutedEventHandler(OnLoaded);
        }        

        void SearchBtn_Click(object sender, RoutedEventArgs e)
        {
            this.Topic = txtSearchTopic.Text;
            SaveState();
            DoSearch();
        }

        void OnLoaded(object sender, RoutedEventArgs e)
        {
            GetState();
        }

        private void DoSearch()
        {
            string topic = txtSearchTopic.Text;
            string diggUrl = String.Format("http://services.digg.com/stories/topic/{0}?count=20&appkey=http%3A%2F%2Fscottgu.com", topic);

            // Initiate Async Network call to Digg
            WebClient diggService = new WebClient();
            diggService.DownloadStringCompleted += new DownloadStringCompletedEventHandler(DiggService_DownloadStoriesCompleted);
            diggService.DownloadStringAsync(new Uri(diggUrl));
        }

        void DiggService_DownloadStoriesCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                DisplayStories(e.Result);
            }
        }

        void DisplayStories(string xmlContent)
        {
            XDocument xmlStories = XDocument.Parse(xmlContent);

            var stories = from story in xmlStories.Descendants("story")
                          where story.Element("thumbnail") != null &&
                                !story.Element("thumbnail").Attribute("src").Value.EndsWith(".gif")
                          select new DiggStory
                          {
                              Id = (int)story.Attribute("id"),
                              Title = ((string)story.Element("title")).Trim(),
                              Description = ((string)story.Element("description")).Trim(),
                              ThumbNail = (string)story.Element("thumbnail").Attribute("src").Value,
                              HrefLink = new Uri((string)story.Attribute("link")),
                              NumDiggs = (int)story.Attribute("diggs"),
                              UserName = (string)story.Element("user").Attribute("name").Value,
                          };

            StoriesList.SelectedIndex = -1;
            StoriesList.ItemsSource = stories.Take(5);
        }

        void StoriesList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            DiggStory story = (DiggStory)StoriesList.SelectedItem;

            if (story != null)
            {
                //DetailsView.DataContext = story;
                //DetailsView.Visibility = Visibility.Visible;
            }
        }
    }
}
